/****************************************************************************
  @file    : remote.c
  @Version : V1.0
  @Company : NULL
  @author  : wandeng
  @date    : 2024-6-21
  @brief   :
*****************************************************************************/

/* Includes ----------------------------------------------------------------*/
#include "remote.h"
#include "aircon.h"

/* Private function prototypes ---------------------------------------------*/

/* Global Variable----------------------------------------------------------*/
uint16_t		IrSendBuf[400];   //红外遥控编码区
IRDEV			IrDev;           //红外发射器状态管理

hw_timer_t * timer = NULL;

void ARDUINO_ISR_ATTR onTimer() {	
	static uint16_t sendcnt = 0;
	static uint16_t sendflag = 0;
	
	if(IrDev.State == IRREMOTE_IDLE) {
		RELOAD_TIME(10000);
	}
	else if(IrDev.State == IRREMOTE_REQUIRE) {
		uint16_t tmp;
		if(sendcnt)sendcnt = sendflag = 0;
		if(sendflag++ <12) {
			PWM_OUT_DISABLE;
			RELOAD_TIME(30000);	//1MHz  30ms
			return;
		}
		sendflag = 0;
		
		sendcnt = 0;
		LED_ON;
		IrDev.State = IRREMOTE_SENDING;
		tmp = IrSendBuf[sendcnt++];

		if(tmp&0x8000) {
		  PWM_OUT_ENABLE;
		}
		else {
		  PWM_OUT_DISABLE;
		}

		timerRestart(timer);
		RELOAD_TIME(tmp);
	} else if(IrDev.State == IRREMOTE_SENDING) {
		if(sendcnt >= IrDev.Len) {  //发送完成
			IrDev.State = IRREMOTE_IDLE;
			IrDev.Len = 0;
			sendcnt = 0;
			PWM_OUT_DISABLE;
			RELOAD_TIME(10000);
			LED_OFF;
		} else {
			uint16_t tmp;

			tmp = IrSendBuf[sendcnt++];

			if(tmp&0x8000) {
			  PWM_OUT_ENABLE;
			}
			else {
			  PWM_OUT_DISABLE;
			}
			RELOAD_TIME(tmp);
		}
	}
}

/* Public functions --------------------------------------------------------*/
void RemoteInit(void) {
	ledcSetup(8, 38000, 10);  //设置LEDC通道8频率为1，分辨率为10位，即占空比可选0~1023
	ledcAttachPin(5, 8); //设置LEDC通道8在IO5上输出
	
	timer = timerBegin(0, 80, true);
	// Attach onTimer function to our timer.
	timerAttachInterrupt(timer, &onTimer, true);
	// Set alarm to call onTimer function every second (value in microseconds).
	// Repeat the alarm (third parameter)
	timerAlarmWrite(timer, 10000, true);

	// Start an alarm
	timerAlarmEnable(timer);
}
